package book.manage.sql;

import book.manage.mapper.BookMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.function.Consumer;

public class SqlUtil {

    private SqlUtil(){}

    private static SqlSessionFactory Factory;

    static {
        try {
            Factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void doSqlWork(Consumer<BookMapper> consumer){// 传入一个BookMapper的消费者
        try(SqlSession session = Factory.openSession(true)){// 创建一个SqlSession对象
            BookMapper bookMapper = session.getMapper(BookMapper.class);
            consumer.accept(bookMapper);
            /* consumer是一个存放的代码块，也就是一个函数，这个函数传入的就是bookMapper
                这样子统一了sql的操作，只需要传入一个函数，就可以执行sql操作
            */
        }

    }

}
